<template>
  <div ref="auto" class="auto-parent">
    <Input
      v-model.trim="currValue"
      class="large"
      :class="className"
      :placeholder="placeholder"
      clearable
      :maxlength="30"
      @on-focus="onFocus"
      @input="onSearch"
      @on-enter="onEnter"
    />
    <div v-if="!custom" class="autocomplete">
      <div
        v-for="(item, i) in data"
        :key="i"
        class="item"
        @click="onSelect(item)"
      >
        {{ item }}
      </div>
    </div>
    <div v-else class="autocomplete">
      <slot />
    </div>
  </div>
</template>

<script>
export default {
  name: 'Suggestion',
  props: {
    placeholder: {
      type: String,
      default: '请输入'

    },
    value: {
      type: [String, Number],
      default: ''
    },
    data: {
      type: Array,
      default: () => []
    },
    className: {
      type: String,
      default: ''
    },
    custom: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      currValue: this.value
    }
  },
  watch: {
    currValue () {
      this.$emit('input', this.currValue)
    },
    value () {
      this.currValue = this.value
    }
  },
  mounted () {
    document.addEventListener('click', this.onDocumentClick)
  },
  destroyed () {
    document.removeEventListener('click', this.onDocumentClick)
  },
  methods: {
    onDocumentClick (e) {
      if (!this.$refs.auto.contains(e.target)) {
        this.$emit('clear')
      }
    },
    onSearch () {
      this.$emit('input', this.currValue)
      this.$emit('searchBefore')
      this.$nextTick(() => this.$emit('search', this.currValue))
    },
    onFocus () {
      this.$emit('focus')
    },
    onSelect (item) {
      this.currValue = item
      this.$emit('input', item)
      this.$nextTick(() => {
        this.$emit('select', item)
        this.$emit('clear')
      })
    },
    onEnter () {
      this.$emit('enter')
    }
  }
}
</script>

